const express = require('express');
// const { get_token } = require('../middleware/checkToken');
const router = express.Router();
const urlib = require("url");

// router.use(function (req, res, next) {
//     let a = require('../app/api/controllers/CourseController');
//     a.get_index(req,res);
// })

router.use(function (req, res, next) {
    if (req.url == '/favicon.ico') {
      res.end('404');
      return;
    }
    // console.log(req.url);
  
    try { 
      let myobj = urlib.parse(req.url, true);
      let name = myobj.pathname;
      let UrlArr = name.split('/');
      // console.log(UrlArr);
      let controllerName = UrlArr[1] ? UrlArr[1] : 'index';
      let actionName = UrlArr[2] ? UrlArr[2] : 'index';
  
      actionName = req.method.toLowerCase() + '_' + actionName;
      // console.log(actionName);
      controllerName = controllerName[0].toUpperCase() + controllerName.substr(1);
      req.actionName = actionName;
      req.controllerName = controllerName;
      // console.log(req);
  
      // console.log(`../app/${req.moduleName}/controllers/${controllerName}Controller`);
      const controllerObj = require(`../app/${req.moduleName}/controllers/${controllerName}Controller`);
      controllerObj[actionName](req, res, next);
    } catch (err) {
      throw err;
    }
  })


module.exports = router;

